#include "common.hpp"

extern Log log;
int main()
{
    //创建共享内存
    int shm_id = create_shm();
    init_fifo init; //创建匿名管道，通知标志

    //挂接共享内存
    char* shm_addr = (char*)shmat(shm_id, NULL, 0); //类似于malloc
    if(shm_addr == (void*)-1)
    {
        log(Fatal, "shm_addr error:%s\n", strerror(errno));
        return -1;
    }

    int fd = open(FIFO_FILE, O_RDONLY); //打开标志接收文件
    if (fd < 0)
    {
        log(Fatal, "Open myfifo error:%s", strerror(errno));
        exit(-1);
    }

    //开始通信
    while(true)
    {
        char flag;
        cout << "client@ " << shm_addr;
        int ret = read(fd, &flag, sizeof(flag));
        if(ret == 0) break;
        else if(ret < 0) break;
        log(Info, "client@ %s\n", shm_addr);
        sleep(1);
    }

    //detach共享内存
    int ret = shmdt(shm_addr);
    if(ret < 0)
    {
        log(Fatal, "shmdt error:%s\n", strerror(errno));
        return -1;
    }

    //删除共享内存
    shmctl(shm_id, IPC_RMID, nullptr);
    close(fd);
    cout << "通信结束！\n" << endl;
    
    return 0;
}